package com.qn.example.service.impl;

import com.qn.example.mapper.ShoppingCartMapper;
import com.qn.example.pojo.ShoppingCart;
import com.qn.example.service.ShoppingCartService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 21276
 * @version 1.0
 * @date 2023/5/23 9:51
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public ShoppingCart add(ShoppingCart shoppingCart) {
        //判断当前用户是否已经存在购物车（菜品购物车或者套餐购物车）
        ShoppingCart dbShoppingCart = shoppingCartMapper.findByUserIdAndDishIdOrSetmeanId(shoppingCart);
        //判断数据库中存不存在该用户的购物车
        if (dbShoppingCart != null) {
            //存在
            dbShoppingCart.setNumber(dbShoppingCart.getNumber() + 1);
            //更新数据库中购物车的数据
            shoppingCartMapper.update(dbShoppingCart);
        } else {
            //不存在
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            //将这个购物车添加到数据库中
            shoppingCartMapper.save(shoppingCart);
            //用新生成的购物车替换查询出来的空购物车
            dbShoppingCart = shoppingCart;
        }
        //返回最新的购物车信息
        return dbShoppingCart;
    }

    @Override
    public List<ShoppingCart> list(Long user) {
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.findShoppingCarById(user);
        return shoppingCartList;
    }

    @Override
    public void clean(Long userId) {
        shoppingCartMapper.deleteByUserId(userId);
    }

    @Override
    public ShoppingCart  deleteShoppingCart(Long dishId, Long setmealId, Long userId) {
        //判断当前用户是否已经存在购物车（菜品购物车或者套餐购物车）
        ShoppingCart dbShoppingCart = shoppingCartMapper.findByUserIdShoppingCart(dishId,setmealId,userId);
        dbShoppingCart.setNumber(dbShoppingCart.getNumber() - 1);
        //判断当前购物车中是否数量大于1
        if (dbShoppingCart.getNumber()>0){
            //更新数据表
            shoppingCartMapper.update(dbShoppingCart);
        }else {
            //删除这条记录
            shoppingCartMapper.delete(dishId,setmealId,userId);
        }
        return dbShoppingCart;
    }
}
